<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/19
 * Time: 17:22
 */

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

class WeChatController extends Controller
{

    public function test(Request $request){
        $code = $request->get('code','');
        $app = app('wechat.mini_program');
        $data = $app->auth->session($code);
        return $this->returnJson(0,'',$data);
    }

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve(Request $request)
    {

        $data = $request->all();
        return $data['echostr'];
        $signature = $data["signature"];
        $timestamp = $data["timestamp"];
        $nonce = $data["nonce"];

        $token = config('wechat.mini_program.default.token');;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if ($tmpStr == $signature ) {
            return true;
        } else {
            return false;
        }
        exit;
        /**
         *   "code" => "001ILdYe0aT4FA1GvRXe0S8bYe0ILdYP"071zOakd1AX75t0q20md1bjfkd1zOakJ
         * "nick" => "大熊"
         * "avaurl" => "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqMhutJzfFErNt8ibicmOco47nqfbvTYHUs0BicYSB6RjOFlxMCSAJSic0PzVQ5555rrBGT5qdG3DcibZQ/132"
         * "sex" => "1"
         * WECHAT_MINI_PROGRAM_APPID=wx2625c12c6420486b
         * WECHAT_MINI_PROGRAM_SECRET=f0eae473c5119fc9fd0046dc700b271d
         */
        $code = $request->get('code',"071zOakd1AX75t0q20md1bjfkd1zOakJ");//小程序传来的code值
        $nick = $request->get('nick',"大熊");//小程序传来的用户昵称
        $imgUrl = $request->get('avaurl','');//小程序传来的用户头像地址
        $sex = $request->get('sex',"1");//小程序传来的用户性别
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx2625c12c6420486b&secret=af4ea46020f5a7b5e90c4d6f827eed1a&js_code=' . $code . '&grant_type=authorization_code';
        //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取；
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
        dd($arr);
        $openid = $arr['openid'];
        $session_key = $arr['session_key'];
        $con = mysqli_connect('localhost', 'root', '123');//连接数据库
        if ($con) {
            if (mysqli_select_db($con, 'students')) {
                $sql1 = "select * from weixin where openid = '$openid'";
                $result = mysqli_query($con, $sql1);
                $result = mysqli_fetch_assoc($result);
                if ($result!=null) {//如果数据库中存在此用户的信息，则不需要重新获取
                    $result = json_encode($result);
                    echo $result;
                }
                else {//没有则将数据存入数据库
                    if ($sex == '0') {
                        $sex = 'none';
                    } else {
                        $sex = '1' ? 'man' : 'women';
                    }
                    $sql = "insert into weixin values ('$nick','$openid','$session_key','$imgUrl','$sex')";
                    if (mysqli_query($con, $sql)) {
                        $arr['nick'] = $nick;
                        $arr['imgUrl'] = $imgUrl;
                        $arr['sex'] = $sex;
                        $arr = json_encode($arr);
                        echo $arr;
                    } else {
                        die('failed' . mysqli_error($con));
                    }
                }
            }
        } else {
            die(mysqli_error());
        }
    }

    public function customerService(){
//        array (
//            'ToUserName' => 'gh_c04bdfcb5dbf',
//            'FromUserName' => 'oOM3i5JP--2n6cszwPrjILJxSMkQ',
//            'CreateTime' => 1541129600,
//            'MsgType' => 'text',
//            'Content' => '浏览器',
//            'MsgId' => 6619101231350326229,
//        )
        $app = app('wechat.mini_program');
        $app->server->push(function ($message) {
            Log::info($message);
            if(isset($message['MsgType'])){
                switch ($message['MsgType']) {
                    case 'event':
                        return '收到事件消息';
                        break;
                    case 'text':
                        //记录数据库
                        //客服消息需要用单独的定时任务做处理，不然会涉及微信重复导致的重复推送
                        $app = app('wechat.mini_program');
                        return $app->customer_service->message(new Text('您好，抽奖进行时为您服务'))
                            ->to($message['FromUserName'])->send();
                        break;
                    case 'image':
                        return '收到图片消息';
                        break;
                    case 'voice':
                        return '收到语音消息';
                        break;
                    case 'video':
                        return '收到视频消息';
                        break;
                    case 'location':
                        return '收到坐标消息';
                        break;
                    case 'link':
                        return '收到链接消息';
                        break;
                    case 'file':
                        return '收到文件消息';
                    default:
                        return '收到其它消息';
                        break;
                }
            }
        });
        $response = $app->server->serve();
        return $response;
    }

}